package com.blog.cloud.auth.utils;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.UUID;

@Component
public class JwtAuthenticationProvider implements AuthenticationProvider {

    private final JwtEncoder jwtEncoder;

    public JwtAuthenticationProvider(JwtEncoder jwtEncoder) {
        this.jwtEncoder = jwtEncoder;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 这里实现账号、邮箱或手机号的验证逻辑
        String username = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();

        // 假设已经成功验证了用户凭证
        boolean isValidUser = validateUserCredentials(username, password);

        if (!isValidUser) {
            throw new BadCredentialsException("Invalid credentials");
        }

        // 创建并返回 JWT
        Instant now = Instant.now();
        String scope = "read write";
        String jti = UUID.randomUUID().toString();
        JwtClaimsSet claims = JwtClaimsSet.builder()
                .issuer("self")
                .issuedAt(now)
                .expiresAt(now.plus(1, ChronoUnit.HOURS))
                .subject(username)
                .claim("scope", scope)
                .jwtId(jti)
                .build();

        String tokenValue = jwtEncoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();

        return new JwtAuthenticationToken(tokenValue, null, Collections.emptyList());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }

    private boolean validateUserCredentials(String username, String password) {
        // 实现具体的验证逻辑
        return true; // 示例代码总是返回 true，请替换为实际验证逻辑
    }
}
